package com.whately.core.httpsession;

import com.google.common.collect.Maps;
import com.whately.core.base.exception.ServiceException;
import com.whately.core.base.utils.AESUtils;
import com.whately.core.base.utils.DateUtil;
import com.whately.core.base.utils.GsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class HeaderTokenHelper {
    private static final Logger logger = LoggerFactory.getLogger(HeaderTokenHelper.class);

    private static final  String key_name_sessionOthers="s2";
    public static String  reCreateNewToken(String sessionId,String uKey,String ip){
        String sessionBegin8Chars=sessionId.substring(0,8);
        String sessionOtherChars=sessionId.substring(8);

        Map<String,String> map= Maps.newHashMap();
        map.put(key_name_sessionOthers,sessionOtherChars);
        map.put("ts",""+DateUtil.nowSecond());
        map.put("ip",ip);
        map.put("uKey",uKey);
        String code = AESUtils.encrypt(getKey(sessionBegin8Chars), GsonUtils.toJsonString(map));

        return sessionBegin8Chars+code ;

    }


    public static String  getSessionIdFromEncodeToken(String encodeToken,String ip){

        try{
            String sessionBegin8Chars=encodeToken.substring(0,8);
            String needDecodeStr= encodeToken.substring(8);
            String decodeStr= AESUtils.decrypt(getKey(sessionBegin8Chars),needDecodeStr);

            Map<String,String> map = GsonUtils.jsonToMaps(decodeStr,String.class);
            String keyLeft=map.get(key_name_sessionOthers);
            if(!StringUtils.equals(ip,map.get("ip"))){
                logger.error("getSessionIdFromEncodeToken error not equal ip {} ,map {}",ip,decodeStr);
            }else{
                if(StringUtils.isNotBlank(keyLeft)){
                    String sessionId=sessionBegin8Chars+keyLeft;
                    return  sessionId;
                }
            }
        }catch (Exception e){
            logger.error("getSessionIdFromEncodeToken error ,encodeToken {} ,error {}",encodeToken,e);
        }
        return "";
    }

    private static  String getKey(String key8Chars){
        if(key8Chars.length()!=8){
            logger.error("token key length error key8Chars {}",key8Chars);
            throw new ServiceException(400,"错误：token key length error");
        }
        String key= key8Chars+"h6t0m34j";
        return key;
    }
}
